<template>
    <el-dialog
        v-model="dialogVisible"
        @close="closeDialog"
        :close-on-click-modal="false"
        :title="dialogTitle"
        width="610px"
    >
        <el-scrollbar height="540" ref="scrollbarRef">
            <el-form
                class="mr8 mt10"
                label-width="120"
                ref="ruleFormRef"
                :rules="rules"
                :model="ruleForm"
            >
                <el-form-item label="等级名称" prop="name">
                    <div>
                        <el-input
                            id="name"
                            v-model="ruleForm.name"
                            show-word-limit
                            :maxlength="12"
                            placeholder="请输入等级名称"
                            clearable
                            class="w220"
                        />
                        <p class="form-tip-color fz11">例如：普通会员、白金会员、钻石会员</p>
                    </div>
                </el-form-item>

                <el-form-item label="等级有效期" :required="!isFirstLevel">
                    <div v-if="isFirstLevel">永久有效</div>
                    <ul v-else>
                        <li class="f-c">
                            <el-radio-group v-model="ruleForm.is_effective" @change="radioChangeIsEffective">
                                <el-radio :value="0">永久有效</el-radio>
                                <el-radio :value="1">自定义有效期</el-radio>
                            </el-radio-group>
                            <el-form-item v-if="isEffectiveCustom" label-width="8" prop="effective_days" class="valid_period__error">
                                <GInputNumber
                                    id="effective_days"
                                    v-model="ruleForm.effective_days"
                                    type="integer"
                                    placeholder="请输入有效期天数"
                                    :maxlength="4"
                                    clearable
                                    class="w120"
                                />
                                <span class="pl8">天</span>
                            </el-form-item>
                        </li>
                        <li class="form-tip-color fz11">自定义有效期，填写0为领取当日24点前有效，填写1为次日24点前有效，以此类推</li>
                    </ul>
                </el-form-item>

                <div v-if="!isSpecial">
                    <el-form-item label="升级至本等级条件" class="mb0" prop="level_up_condition" :inline-message="true">
                        <span v-if="levelDetail.index === 0" class="mb18">注册</span>
                        <el-radio-group v-else v-model="ruleForm.level_up_condition" @change="radioChangeLevelUpCondition">
                            <el-radio :value="1">积分</el-radio>
                            <el-radio :value="2">消费</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <ul v-if="levelDetail.index > 0" class="mt8">
                        <li v-if="ruleForm.level_up_condition === 1">
                            <el-form-item>
                                <el-checkbox v-model="ruleFormComponent.day_point_claim" @change="checkChangeDayPointClaim">成为LV.{{ levelDetail.index }}后单日累计获取</el-checkbox>
                                <el-form-item v-if="ruleFormComponent.day_point_claim" label-width="8" prop="day_point_claim">
                                    <GInputNumber
                                        id="day_point_claim"
                                        v-model="ruleForm.day_point_claim"
                                        type="upInteger"
                                        placeholder="请输入积分数量"
                                        :maxlength="8"
                                        clearable
                                        class="w120"
                                    />
                                    <span class="pl8">积分</span>
                                </el-form-item>
                            </el-form-item>
                            <el-form-item>
                                <el-checkbox v-model="ruleFormComponent.point_claim" @change="checkChangePointClaim">成为LV.{{ levelDetail.index }}后累计获取</el-checkbox>
                                <el-form-item v-if="ruleFormComponent.point_claim" label-width="8" prop="point_claim">
                                    <GInputNumber
                                        id="point_claim"
                                        v-model="ruleForm.point_claim"
                                        type="upInteger"
                                        placeholder="请输入积分数量"
                                        :maxlength="8"
                                        clearable
                                        class="w120"
                                    />
                                    <span class="pl8">积分</span>
                                </el-form-item>
                            </el-form-item>
                            <div v-if="ruleFormComponent.day_point_claim && ruleFormComponent.point_claim" class="pl60">
                                <el-form-item label="两者关系">
                                    <el-radio-group v-model="ruleForm.point_relation">
                                        <el-radio :value="1">满足其一即可</el-radio>
                                        <el-radio :value="0">同时满足</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </div>
                        </li>
                        <li v-if="ruleForm.level_up_condition === 2">
                            <el-form-item>
                                <el-checkbox v-model="ruleFormComponent.day_cost_claim" @change="checkChangeDayCostClaim">成为LV.{{ levelDetail.index }}后单日累计消费</el-checkbox>
                                <el-form-item v-if="ruleFormComponent.day_cost_claim" label-width="8" prop="day_cost_claim">
                                    <GInputNumber
                                        id="day_cost_claim"
                                        v-model="ruleForm.day_cost_claim"
                                        type="decimal"
                                        placeholder="请输入消费金额"
                                        :max="99999999.99"
                                        clearable
                                        class="w120"
                                    />
                                    <span class="pl8">元</span>
                                </el-form-item>
                            </el-form-item>
                            <el-form-item>
                                <el-checkbox v-model="ruleFormComponent.year_cost_claim" @change="checkChangeYearCostClaim">成为LV.{{ levelDetail.index }}后累计消费</el-checkbox>
                                <el-form-item v-if="ruleFormComponent.year_cost_claim" label-width="8" prop="year_cost_claim">
                                    <GInputNumber
                                        id="year_cost_claim"
                                        v-model="ruleForm.year_cost_claim"
                                        type="decimal"
                                        placeholder="请输入消费金额"
                                        :max="99999999.99"
                                        clearable
                                        class="w120"
                                    />
                                    <span class="pl8">元</span>
                                </el-form-item>
                            </el-form-item>
                            <div v-if="ruleFormComponent.day_cost_claim && ruleFormComponent.year_cost_claim" class="pl60">
                                <el-form-item label="两者关系">
                                    <el-radio-group v-model="ruleForm.cost_relation">
                                        <el-radio :value="1">满足其一即可</el-radio>
                                        <el-radio :value="0">同时满足</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </div>
                        </li>
                    </ul>
                </div>

                <el-form-item label="保级条件" class="mb0" :required="showAnimalRetain">
                    <span v-if="!(showAnimalRetain)" class="mb18">无</span>
                    <el-radio-group v-else class="mb8" v-model="ruleFormComponent.animalRetain" @change="radioChangeAnimalRetain">
                        <el-radio :value="1">积分</el-radio>
                        <el-radio :value="2">消费</el-radio>
                    </el-radio-group>
                </el-form-item>

                <div v-if="showAnimalRetain">
                    <el-form-item v-if="ruleFormComponent.animalRetain === 1">
                        <span>成为LV.{{ levelDetail.index + 1 }}后有效期内获取</span>
                        <el-form-item label-width="8" prop="point_retain">
                            <GInputNumber
                                id="point_retain"
                                v-model="ruleForm.point_retain"
                                type="upInteger"
                                placeholder="请输入所需积分"
                                :maxlength="8"
                                clearable
                                class="w120"
                            />
                            <span class="pl8">积分</span>
                        </el-form-item>
                    </el-form-item>
                    <el-form-item v-if="ruleFormComponent.animalRetain === 2">
                        <span>成为LV.{{ levelDetail.index + 1 }}后有效期内累计消费</span>
                        <el-form-item label-width="8" prop="cost_retain">
                            <GInputNumber
                                id="cost_retain"
                                v-model="ruleForm.cost_retain"
                                type="decimal"
                                placeholder="请输入消费金额"
                                :max="99999999.99"
                                clearable
                                class="w120"
                            />
                            <span class="pl8">元</span>
                        </el-form-item>
                    </el-form-item>
                </div>

                <el-form-item label="会员卡卡面" required class="mb8">
                    <div>
                        <el-radio-group v-model="ruleForm.card_style" @change="radioChangeCardStyle">
                            <el-radio :value="0">默认</el-radio>
                            <el-radio :value="1">自定义样式</el-radio>
                        </el-radio-group>
                        <div v-if="ruleForm.card_style === 0" class="mt10">
                            <el-image v-if="customizeTemplate === 1" class="card__container" src="https://cdn.zhimatech.com/bg-black-youxiao-three.png"/>
                            <el-image v-else class="card__container" src="https://cdn.zhimatech.com/ba-red-youxiao-three.png"/>
                        </div>
                        <ul v-if="ruleForm.card_style === 1" class="mt10">
                            <li class="pb15">
                                <el-form-item label-width="84" label="卡面字体颜色">
                                    <el-input type="color" v-model="ruleForm.card_color" style="width: 48px;"/>
                                </el-form-item>
                            </li>
                            <li>
                                <el-form-item label-width="96" prop="card_img_url" :required="false" label="会员卡卡面背景">
                                    <div class="mt3">
                                        <upload-image-video v-model="ruleForm.card_img_url"/>
                                        <p class="form-tip-color fz11 pt5">*建议尺寸686x320dpi，不超过1M，支持jpg, jpeg, png格式</p>
                                    </div>
                                </el-form-item>
                                <el-form-item class="mt25">
                                    <ul
                                        class="card__container card__container--customize border-a b-box"
                                        :style="{ color: ruleForm.card_color, background: `url(${ruleForm.card_img_url}) no-repeat top/cover` }"
                                    >
                                        <li class="f-c-b">
                                            <div class="f-c">
                                                <el-image class="card__avatar" src="https://cdn.zhimatech.com/icon-head.png"/>
                                                <span class="card__nickname">昵称</span>
                                            </div>
                                            <p class="card__code"/>
                                        </li>
                                        <li class="f-c-b">
                                            <div class="flex text-c">
                                                <div>
                                                    <p class="card__title--large">1888</p>
                                                    <p class="line-h18">积分</p>
                                                </div>
                                                <div class="ml20">
                                                    <p class="card__title--large">8</p>
                                                    <p class="line-h18">优惠券</p>
                                                </div>
                                            </div>
                                            <div class="text-r">
                                                <p class="card__title--large">会员等级</p>
                                                <p v-if="!isEffectiveCustom" class="line-h18">永久有效</p>
                                                <p v-else class="line-h18">2020.12.31 到期</p>
                                            </div>
                                        </li>
                                    </ul>
                                </el-form-item>
                            </li>
                        </ul>
                    </div>
                </el-form-item>

                <el-form-item label="消费送多倍积分" class="mt18 mb0">
                    <ul>
                        <li class="form-tip-color pb10">*适用于线上线下消费赠送积分，例如设置日常生日当日积分翻2倍，则原本可获得10积分的消费，在生日当天送20积分</li>
                        <li v-for="row in checkboxValue" :key="row.key">
                            <div class="f-c pb20">
                                <el-checkbox v-model="ruleFormComponent[row.key]" @change="checkChangeMultiple(row)">
                                    <span>{{ row.label || '' }}</span>
                                    <span v-if="ruleFormComponent[row.key]">{{ row.checkTrueLabel || '' }}</span>
                                    <span v-else>{{ row.checkFalseLabel || '' }}多倍积分</span>
                                </el-checkbox>
                                <div v-if="ruleFormComponent[row.key]" class="f-c">
                                    <!--每年固定月份多倍积分-->
                                    <el-form-item v-if="row.dateKey === 'year_months'" label-width="8" :prop="row.dateKey">
                                        <el-select v-model="ruleForm[row.dateKey]" clearable multiple collapse-tags collapse-tags-tooltip class="w140">
                                            <el-option v-for="row in 12" :key="row" :value="row" :label="`${row}月`"/>
                                        </el-select>
                                        <span class="pl8">积分</span>
                                    </el-form-item>
                                    <!--每年固定日期多倍积分-->
                                    <el-form-item v-if="row.dateKey === 'year_day_periods'" label-width="8" :prop="row.dateKey">
                                        <PickerMonthDay v-model="ruleForm[row.dateKey]"/>
                                        <span class="pl8">积分</span>
                                    </el-form-item>
                                    <!--每月固定周多倍积分-->
                                    <el-form-item v-if="row.dateKey === 'month_weeks'" label-width="8" :prop="row.dateKey">
                                        <el-select v-model="ruleForm[row.dateKey]" clearable multiple collapse-tags collapse-tags-tooltip class="w140">
                                            <el-option v-for="row in 6" :key="row" :value="row" :label="`第${largeNumber[row]}周`"/>
                                        </el-select>
                                        <span class="pl8">积分</span>
                                    </el-form-item>
                                    <!--每月固定日多倍积分-->
                                    <el-form-item v-if="row.dateKey === 'month_days'" label-width="8" :prop="row.dateKey">
                                        <el-select v-model="ruleForm[row.dateKey]" clearable multiple collapse-tags collapse-tags-tooltip class="w140">
                                            <el-option v-for="row in 31" :key="row" :value="row" :label="`${row}日`"/>
                                        </el-select>
                                        <span class="pl8">积分</span>
                                    </el-form-item>
                                    <!--每周固定日多倍积分-->
                                    <el-form-item v-if="row.dateKey === 'week_days'" label-width="8" :prop="row.dateKey">
                                        <el-select v-model="ruleForm[row.dateKey]" clearable multiple collapse-tags collapse-tags-tooltip class="w140">
                                            <el-option v-for="row in 6" :key="row" :value="row" :label="`周${largeNumber[row]}`"/>
                                            <el-option :value="7" label="周日"/>
                                        </el-select>
                                        <span class="pl8">积分</span>
                                    </el-form-item>
                                    <!--自定义时间段多倍积分-->
                                    <el-form-item v-if="row.dateKey === 'customize_time_periods'" label-width="8" :prop="row.dateKey">
                                        <el-date-picker
                                            v-model="ruleForm[row.dateKey]"
                                            type="daterange"
                                            range-separator="-"
                                            start-placeholder="开始时间"
                                            end-placeholder="结束时间"
                                            value-format="YYYY-MM-DD"
                                            :editable="false"
                                            style="width: 230px"
                                        />
                                        <span class="pl8">积分</span>
                                    </el-form-item>

                                    <el-form-item label-width="8" :prop="row.key">
                                        <GInputNumber
                                            v-model="ruleForm[row.key]"
                                            type="decimal"
                                            placeholder="请输入"
                                            :max="99999999.99"
                                            clearable
                                            class="w100"
                                        />
                                        <span class="pl8">倍</span>
                                    </el-form-item>
                                </div>
                            </div>
                        </li>
                    </ul>
                </el-form-item>

                <el-form-item label="会员等级礼">
                    <ul>
                        <li class="f-c pb20">
                            <el-checkbox
                                v-model="ruleForm.reward_point_switch"
                                :true-value="2"
                                :false-value="1"
                                @change="checkChangeRewardPoint"
                            >
                                达到等级送积分
                            </el-checkbox>
                            <el-form-item v-if="ruleForm.reward_point_switch === 2" label-width="8" prop="reward_point_num">
                                <GInputNumber
                                    v-model="ruleForm.reward_point_num"
                                    type="upInteger"
                                    placeholder="请输入积分"
                                    :maxlength="12"
                                    clearable
                                    class="w120"
                                />
                                <span class="pl8">积分</span>
                            </el-form-item>
                        </li>
                        <li>
                            <div class="f-c">
                                <el-checkbox v-model="ruleFormComponent.giftsCheck" @change="checkChangeGifts">达到等级送优惠券</el-checkbox>
                                <el-button
                                    v-if="ruleFormComponent.giftsCheck"
                                    type="primary"
                                    :icon="Plus"
                                    class="ml15"
                                    @click="showCheckCouponDialog"
                                >
                                    增加优惠券
                                </el-button>
                            </div>
                            <el-form-item v-if="ruleFormComponent.giftsCheck" prop="gifts" class="ml20">
                                <div v-if="!!ruleForm.gifts?.length">
                                    <el-tag
                                        v-for="(row,i) in ruleForm.gifts"
                                        size="default"
                                        :key="row.id"
                                        closable
                                        class="mt12 mr12"
                                        @close="removeGifts(i)"
                                    >
                                        {{ row.name }}
                                    </el-tag>
                                </div>
                            </el-form-item>
                        </li>
                    </ul>
                </el-form-item>
            </el-form>
        </el-scrollbar>

        <template #footer>
            <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            <el-button class="mr8" type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
        </template>
    </el-dialog>

    <CheckCoupon
        :max="3"
        :ids="ruleFormComponent.gifts"
        :concatData="concatGifts"
        v-model="checkCouponDialog"
        :params="{ expired: 0, purpose: 4, has_not_used: 1, group_ids: '[1,2,3]', statuses: [1,2] }"
        @change="changeGifts"
    />
</template>

<script setup lang="ts">
    import { ref, reactive, watch, PropType, nextTick, computed } from "vue";
    import { Plus } from "@element-plus/icons-vue";
    import { _mallStore } from "@/store/config";
    import PickerMonthDay from "@/components/form/PickerMonthDay.vue"
    import CheckCoupon from "@/components/checkDialog/CheckCoupon.vue"
    import UploadImageVideo from "@/components/global/UploadImageVideo.vue";

    const props = defineProps({
        modelValue: {
            type: Boolean,
            default: false,
        },
        isSpecial: {
            type: Boolean,
            default: false,
        },
        detail: {
            type: Object as PropType<ObjValueAny>,
            default: () => {
                return {}
            }
        },
    })

    // 第一个会员等级 等级有效期 显示 永久有效
    const isFirstLevel = computed(() => {
        return props.isSpecial || levelDetail.value.index === 0;
    })

    // 等级有效期 自定义有效期
    const isEffectiveCustom = computed(() => {
        return ruleForm.is_effective === 1;
    })

    // 显示 保级条件
    const showAnimalRetain = computed(() => {
        return isEffectiveCustom.value && !props.isSpecial;
    })

    const customizeTemplate = computed(() => {
        return +_mallStore.mallZeusConfig?.miniapp?.customize_template;
    })

    const emit = defineEmits(['update:modelValue', 'change']);
    let dialogVisible = ref<boolean>(false);// 显示弹窗
    // 关闭弹窗
    const closeDialog = () => {
        cancelDialog();
        emit('update:modelValue', dialogVisible.value);
    }
    // 关闭弹窗
    const cancelDialog = () => {
        dialogVisible.value = false;
    }

    const largeNumber = reactive<string[]>(['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']);
    const checkboxValue = reactive<ObjValueAny[]>([
        { key: 'multiple', label: '日常', checkTrueLabel: '积分' },
        { key: 'holiday_multiple', label: '法定节假日', checkTrueLabel: '积分' },
        { key: 'birthday_multiple', label: '生日当日', checkTrueLabel: '积分' },
        { key: 'birthday_month_multiple', label: '生日当月', checkTrueLabel: '积分' },
        { key: 'fixed_year_month_multiple', dateKey: 'year_months', label: '每年', checkFalseLabel: '固定月份' },
        { key: 'fixed_year_day_multiple', dateKey: 'year_day_periods', label: '每年', checkFalseLabel: '固定日期' },
        { key: 'fixed_month_week_multiple', dateKey: 'month_weeks', label: '每月', checkFalseLabel: '固定周' },
        { key: 'fixed_month_day_multiple', dateKey: 'month_days', label: '每月', checkFalseLabel: '固定日' },
        { key: 'fixed_week_day_multiple', dateKey: 'week_days', label: '每周', checkFalseLabel: '固定日' },
        { key: 'customize_time_period_multiple', dateKey: 'customize_time_periods', checkFalseLabel: '自定义时间段' },
    ])

    const ruleFormInitData = reactive<{ key: string, value?: null | number | string }[]>([
        { key: 'name' }, // 等级名称
        { key: 'is_effective', value: 1 }, // 等级有效期
        { key: 'effective_days' }, // 等级有效期
        { key: 'level_up_condition', value: 1 }, // 升级至本等级条件 积分/消费
        { key: 'day_point_claim' }, // 升级至本等级条件 积分
        { key: 'point_claim' }, // 升级至本等级条件 积分
        { key: 'point_relation', value: 1 }, //升级至本等级条件 积分 两者关系
        { key: 'day_cost_claim' }, // 升级至本等级条件 消费
        { key: 'year_cost_claim' }, // 升级至本等级条件 消费
        { key: 'cost_relation', value: 1 }, // 升级至本等级条件 消费 两者关系
        { key: 'point_retain' }, // 保级条件 积分
        { key: 'cost_retain' }, // 保级条件 消费
        { key: 'card_style', value: 0, }, // 会员卡卡面
        { key: 'card_color', value: '' }, // 卡面字体颜色
        { key: 'card_img_url' }, // 卡面背景图
        { key: 'reward_point_switch', value: 1 }, // 达到等级送积分
        { key: 'reward_point_num' }, // 达到等级送积分
    ])

    const radioChangeCardStyle = () => {
        ruleForm.card_color = '#FFFFFF';
        ruleForm.card_img_url = '';
        if (ruleForm.card_style === 1) {
            nextTick(() => {
                ruleFormRef.value.validateField('card_img_url', () => {
                })
            })
        }
    }

    // 等级有效期 永久有效/自定义有效期  切换
    const radioChangeIsEffective = () => {
        ruleForm.effective_days = '';
        ruleFormComponent.animalRetain = 1;
        radioChangeAnimalRetain();
        if (isEffectiveCustom.value) {
            nextTick(() => {
                ruleFormRef.value.validateField('effective_days', () => {
                })
            })
        }
    }

    // 升级条件 积分/消费 切换
    const radioChangeLevelUpCondition = () => {
        ruleFormComponent.day_point_claim = false;
        ruleFormComponent.point_claim = false;
        ruleFormComponent.day_cost_claim = false;
        ruleFormComponent.year_cost_claim = false;
        checkChangeDayPointClaim();
        checkChangePointClaim();
        checkChangeDayCostClaim();
        checkChangeYearCostClaim();
    }

    const checkChangeDayPointClaim = () => {
        ruleForm.day_point_claim = '';
        resetRelation();
        if (ruleFormComponent.day_point_claim) {
            ruleFormRef.value.validateField('day_point_claim', () => {
            })
        }
    }
    const checkChangePointClaim = () => {
        ruleForm.point_claim = '';
        resetRelation();
        if (ruleFormComponent.point_claim) {
            ruleFormRef.value.validateField('point_claim', () => {
            })
        }
    }
    const checkChangeDayCostClaim = () => {
        ruleForm.day_cost_claim = '';
        resetRelation();
        if (ruleFormComponent.day_cost_claim) {
            ruleFormRef.value.validateField('day_cost_claim', () => {
            })
        }
    }
    const checkChangeYearCostClaim = () => {
        ruleForm.year_cost_claim = '';
        resetRelation();
        if (ruleFormComponent.year_cost_claim) {
            ruleFormRef.value.validateField('year_cost_claim', () => {
            })
        }
    }
    // 升级至本等级条件 两者关系
    const resetRelation = () => {
        ruleForm.point_relation = 1; // 积分
        ruleForm.cost_relation = 1; // 消费
        ruleFormRef.value.validateField('level_up_condition', () => {
        })
    }

    // 保级条件 积分/消费 切换
    const radioChangeAnimalRetain = () => {
        ruleForm.point_retain = '';
        ruleForm.cost_retain = '';
        if (ruleFormComponent.animalRetain === 1) {
            ruleFormRef.value.validateField('point_retain', () => {
            })
        }
        if (ruleFormComponent.animalRetain === 2) {
            ruleFormRef.value.validateField('cost_retain', () => {
            })
        }
    }

    // 倍数
    const checkChangeMultiple = (row: ObjValueAny) => {
        ruleForm[row.key] = '';
        if (row.dateKey) {
            ruleForm[row.dateKey] = [];
        }
        if (ruleFormComponent[row.key]) {
            nextTick(() => {
                ruleFormRef.value.validateField(row.key, () => {
                })
                if (row.dateKey) {
                    ruleFormRef.value.validateField(row.dateKey, () => {
                    })
                }
            })
        }
    }

    let checkCouponDialog = ref<boolean>(false);
    const showCheckCouponDialog = () => {
        checkCouponDialog.value = true;
    }

    const checkChangeRewardPoint = () => {
        ruleForm.reward_point_num = '';
        if (ruleForm.reward_point_switch === 2) {
            nextTick(() => {
                ruleFormRef.value.validateField('reward_point_num', () => {
                })
            })
        }
    }

    const checkChangeGifts = () => {
        ruleFormComponent.gifts = [];
        ruleForm.gifts = [];
        giftsRule();
    }
    const changeGifts = (data: ObjValueAny[]) => {
        ruleForm.gifts = data;
        getGiftsIds();
        giftsRule();
    }
    const removeGifts = (i: number) => {
        ruleForm.gifts.splice(i, 1);
        getGiftsIds();
        giftsRule();
    }
    const getGiftsIds = () => {
        ruleFormComponent.gifts = ruleForm.gifts.map((row: ObjValueAny) => row.id);
    }
    const giftsRule = () => {
        if (ruleFormComponent.giftsCheck) {
            nextTick(() => {
                ruleFormRef.value.validateField('gifts', () => {
                })
            })
        }
    }

    // 表单验证 字段 ===========================================================================
    const validatorFormEmpty = (message: string) => {
        return (rule: ObjValueAny, value: string | number, callback: Function) => {
            if (subStatus && value !== 0 && !value) {
                return callback(new Error(message))
            }
            callback()
        }
    };
    // 等级有效期 验证
    const validateEffectiveDays = (rule: ObjValueAny, value: string, callback: Function) => {
        if (subStatus && isEffectiveCustom.value && !value) {
            return callback(new Error('请输入有效期天数'));
        }
        callback()
    }
    // 升级至本等级条件 验证
    const validateLevelUpCondition = (rule: ObjValueAny, value: number, callback: Function) => {
        if (subStatus && !props.isSpecial && levelDetail.value.index > 0) {
            if (
                (ruleForm.level_up_condition === 1 && !ruleFormComponent.day_point_claim && !ruleFormComponent.point_claim) ||
                (ruleForm.level_up_condition === 2 && !ruleFormComponent.day_cost_claim && !ruleFormComponent.year_cost_claim)
            ) {
                return callback(new Error('请设置升级本等级条件'));
            }
        }
        callback()
    }
    // 升级至本等级条件/积分 验证
    const validateDayPointClaim = (rule: ObjValueAny, value: string, callback: Function) => {
        if (subStatus && ruleFormComponent.day_point_claim) {
            if (!value) {
                return callback(new Error('请输入单日累计升级积分'));
            }
            if (+value <= 0) {
                return callback(new Error('单日累计升级积分需大于0'));
            }
        }
        callback()
    }
    // 升级至本等级条件/积分 验证
    const validatePointClaim = (rule: ObjValueAny, value: string, callback: Function) => {
        if (subStatus && ruleFormComponent.point_claim) {
            if (!value) {
                return callback(new Error('请输入累计升级积分'));
            }
            if (+value <= 0) {
                return callback(new Error('累计升级积分需大于0'));
            }
        }
        callback()
    }
    // 升级至本等级条件/消费 验证
    const validateDayCostClaim = (rule: ObjValueAny, value: string, callback: Function) => {
        if (subStatus && ruleFormComponent.day_cost_claim) {
            if (!value) {
                return callback(new Error('请输入单日累计升级金额'));
            }
            if (+value <= 0) {
                return callback(new Error('单日累计升级金额需大于0'));
            }
        }
        callback()
    }
    // 升级至本等级条件/消费 验证
    const validateYearCostClaim = (rule: ObjValueAny, value: string, callback: Function) => {
        if (subStatus && ruleFormComponent.year_cost_claim) {
            if (!value) {
                return callback(new Error('请输入累计升级金额'));
            }
            if (+value <= 0) {
                return callback(new Error('累计升级金额需大于0'));
            }
        }
        callback()
    }
    // 保级条件/积分 验证
    const validatePointRetain = (rule: ObjValueAny, value: string, callback: Function) => {
        if (subStatus && ruleFormComponent.animalRetain === 2) {
            if (!value) {
                return callback(new Error('请输入所需积分'));
            }
            if (+value <= 0) {
                return callback(new Error('所需积分需大于0'));
            }
        }
        callback()
    }
    // 保级条件/消费 验证
    const validateCostRetain = (rule: ObjValueAny, value: string, callback: Function) => {
        if (subStatus && ruleFormComponent.animalRetain === 3) {
            if (!value) {
                return callback(new Error('请输入消费金额'));
            }
            if (+value <= 0) {
                return callback(new Error('消费金额需大于0'));
            }
        }
        callback()
    }
    // 会员卡卡面 验证
    const validateCardImgUrl = (rule: ObjValueAny, value: string, callback: Function) => {
        if (subStatus && ruleForm.card_style === 1 && !value) {
            if (!value) {
                return callback(new Error('请上传自定义图片'));
            }
        }
        callback()
    }
    // 多倍积分 验证
    const validateMultiple = (key: string = 'multiple') => {
        return (rule: ObjValueAny, value: string | number, callback: Function) => {
            if (subStatus && ruleFormComponent[key]) {
                if (!value) {
                    return callback(new Error('请输入倍数'));
                }
                if (+value <= 1) {
                    return callback(new Error('倍数需大于1.00'));
                }
            }
            callback()
        }
    };

    // 多倍积分时间 验证
    const validateMultipleDate = (key: string, message: string) => {
        return (rule: ObjValueAny, value: string[] | number[], callback: Function) => {
            if (subStatus && ruleFormComponent[key]) {
                if (!value || !value.length) {
                    return callback(new Error(`请选择${message}`));
                }
            }
            callback()
        }
    };
    // 会员等级礼 达到等级送积分
    const validateRewardPointNum = (rule: ObjValueAny, value: string, callback: Function) => {
        if (subStatus && ruleForm.reward_point_switch === 2) {
            if (!value) {
                return callback(new Error('请输入赠送积分'));
            }
            if (+value <= 0) {
                return callback(new Error('赠送积分需大于0'));
            }
        }
        callback()
    }
    // 会员等级礼 达到等级送优惠券
    const validateGifts = (rule: ObjValueAny, value: ObjValueAny[], callback: Function) => {
        if (subStatus && ruleFormComponent.giftsCheck) {
            if (!value.length) {
                return callback(new Error('请选择优惠券'));
            }
        }
        callback()
    }
    const rules = reactive<ObjValueAny>({
        name: [{ required: true, validator: validatorFormEmpty('请输入等级名称'), trigger: 'change' }],
        effective_days: [{ required: true, validator: validateEffectiveDays, trigger: 'change' }],
        level_up_condition: [{ required: true, validator: validateLevelUpCondition, trigger: 'change' }],
        day_point_claim: [{ required: true, validator: validateDayPointClaim, trigger: 'change' }],
        point_claim: [{ required: true, validator: validatePointClaim, trigger: 'change' }],
        day_cost_claim: [{ required: true, validator: validateDayCostClaim, trigger: 'change' }],
        year_cost_claim: [{ required: true, validator: validateYearCostClaim, trigger: 'change' }],
        point_retain: [{ required: true, validator: validatePointRetain, trigger: 'change' }],
        cost_retain: [{ required: true, validator: validateCostRetain, trigger: 'change' }],
        card_img_url: [{ required: true, validator: validateCardImgUrl, trigger: 'change' }],

        reward_point_num: [{ required: true, validator: validateRewardPointNum, trigger: 'change' }],
        gifts: [{ required: true, validator: validateGifts, trigger: 'change' }],
    });

    let ruleForm = reactive<ObjValueAny>({});
    let ruleFormComponent = reactive<ObjValueAny>({});
    let concatGifts = ref<number[]>([]);
    const initRuleForm = () => {
        ruleForm.level_up_condition = 1;// 升级至本等级条件
        ruleFormComponent.day_point_claim = false;// 升级至本等级条件 积分
        ruleFormComponent.point_claim = false;// 升级至本等级条件 积分
        ruleFormComponent.day_cost_claim = false;// 升级至本等级条件 消费
        ruleFormComponent.year_cost_claim = false;// 升级至本等级条件 消费
        ruleFormComponent.animalRetain = 1;// 保级条件
        ruleFormComponent.point_retain = false;// 保级条件 积分
        ruleFormComponent.cost_retain = false;// 保级条件 消费
        ruleFormComponent.reward_point_switch = false;// 达到等级送积分
        ruleFormComponent.giftsCheck = false;// 达到等级送优惠券
        ruleFormComponent.gifts = []// 达到等级送优惠券

        for (let row of ruleFormInitData) {
            ruleForm[row.key] = row.value || row.value === 0 ? row.value : '';
        }
        radioChangeCardStyle();
        ruleForm.gifts = [];
        for (let row of checkboxValue) {
            ruleForm[row.key] = '';
            ruleFormComponent[row.key] = false;
            rules[row.key] = [{ required: true, validator: validateMultiple(row.key), trigger: 'change' }];
            if (row.dateKey) {
                ruleForm[row.dateKey] = [];
                rules[row.dateKey] = [
                    { required: true, validator: validateMultipleDate(row.key, `${row.label || ''}${row.checkFalseLabel}`), trigger: 'change' }
                ];
            }
        }
    }

    const ruleFormRef = ref();
    let subStatus: boolean = false;
    // 表单验证
    const submitForm = async (formEl: any) => {
        subStatus = true;
        if (!formEl) return;
        await formEl.validate((valid: boolean, fields: ObjValueAny) => {
            if (valid) {
                console.log('submit!');
                onSave();
            } else {
                console.log('error submit!', fields)
            }
        });
    }

    const onSave = () => {
        const query: ObjValueAny = submitFormHandlerData();
        resetForm(ruleFormRef.value);
        emit('change', query);
    }
    const submitFormHandlerData = () => {
        const query: ObjValueAny = JSON.parse(JSON.stringify(ruleForm));
        if (query.year_day_periods?.length) {
            query.year_day_periods = {
                start_day: ruleForm.year_day_periods[0],
                end_day: ruleForm.year_day_periods[1],
            };
        } else {
            query.year_day_periods = {};
        }
        if (query.customize_time_periods?.length) {
            query.customize_time_periods = {
                start_day: ruleForm.customize_time_periods[0],
                end_day: ruleForm.customize_time_periods[1],
            };
        } else {
            query.customize_time_periods = {};
        }
        return query;
    }

    const resetForm = (formEl: any) => {
        if (!formEl) return
        cancelDialog();
        formEl.resetFields()
    }

    let levelDetail = ref<ObjValueAny>({});
    const dialogTitle = computed(() => {
        const _beforeTitle: string = levelDetail.value.edit ? '编辑' : '新增';
        if (props.isSpecial) {
            return `${_beforeTitle}特殊等级`;
        } else {
            return `${_beforeTitle}等级 Lv.${levelDetail.value.index + 1}`;
        }
    })

    const scrollbarRef = ref();
    watch(() => props.modelValue, (bool: boolean) => {
        dialogVisible.value = bool;
        if (bool) {
            nextTick(() => {
                scrollbarRef.value!.setScrollTop(0);
            })
            subStatus = false;
            initRuleForm();
            concatGifts.value = [];
            levelDetail.value = props.detail as ObjValueAny;
            if (levelDetail.value.edit) {
                for (let row of ruleFormInitData) {
                    if (levelDetail.value[row.key] || levelDetail.value[row.key] === 0) {
                        ruleForm[row.key] = levelDetail.value[row.key];
                    } else {
                        if (row.value || row.value === 0) {
                            ruleForm[row.key] = row.value;
                        } else {
                            ruleForm[row.key] = '';
                        }
                    }
                }
                // 升级至本等级条件 ============================================================
                // 积分
                ruleFormComponent.day_point_claim = !!ruleForm.day_point_claim;
                ruleFormComponent.point_claim = !!ruleForm.point_claim;
                if (ruleFormComponent.day_point_claim || ruleFormComponent.point_claim) {
                    ruleForm.level_up_condition = 1;
                }
                // 消费
                ruleFormComponent.day_cost_claim = !!ruleForm.day_cost_claim;
                ruleFormComponent.year_cost_claim = !!ruleForm.year_cost_claim;
                if (ruleFormComponent.day_cost_claim || ruleFormComponent.year_cost_claim) {
                    ruleForm.level_up_condition = 2;
                }
                // 保级条件 ============================================================
                // 积分
                ruleFormComponent.point_retain = !!ruleForm.point_retain;
                if (ruleFormComponent.point_retain || ruleFormComponent.point_retain) {
                    ruleFormComponent.animalRetain = 1;
                }
                // 消费
                ruleFormComponent.cost_retain = !!ruleForm.cost_retain;
                if (ruleFormComponent.cost_retain || ruleFormComponent.cost_retain) {
                    ruleFormComponent.animalRetain = 2;
                }
                for (let row of checkboxValue) {
                    if (+levelDetail.value[row.key] > 1) {
                        ruleForm[row.key] = levelDetail.value[row.key];
                        ruleFormComponent[row.key] = true;
                        if (row.dateKey) {
                            if (row.dateKey === 'year_day_periods' || row.dateKey === 'customize_time_periods') {
                                ruleForm[row.dateKey] = [levelDetail.value[row.dateKey].start_day, levelDetail.value[row.dateKey].end_day];
                            } else {
                                ruleForm[row.dateKey] = levelDetail.value[row.dateKey];
                            }
                        }
                    }
                }
                if (levelDetail.value.gifts?.length) {
                    ruleFormComponent.giftsCheck = true;
                    ruleForm.gifts = levelDetail.value.gifts;
                    concatGifts.value = JSON.parse(JSON.stringify(levelDetail.value.gifts));
                    getGiftsIds();
                }
            }
            if (props.isSpecial) {
                ruleForm.is_effective = 0;
            }
        }
    })
</script>

<style scoped lang="scss">
    .pl60 {
        padding-left: 60px;
    }

    /* 表单报错文案 不换行 */
    :deep(.el-form-item__error) {
        white-space: nowrap;
    }

    :deep(.el-form-item__error.el-form-item__error--inline) {
        padding-top: 0;
    }

    .valid_period__error :deep(.el-form-item__error) {
        padding-top: 21px;
    }

    .card__container {
        width: 343px;
        height: 160px;
    }

    .card__container--customize {
        @include flex;
        @include justify-between;
        @include f-column;
        padding: 18px 24px 12px;
        border-radius: 10px;
    }

    .card__avatar {
        width: 54px;
        height: 54px;
        border-radius: 50%;
        border: 2px solid #FFFFFF;
    }

    .card__nickname {
        font-size: 20px;
        font-weight: 600;
        padding-left: 15px;
    }

    .card__code {
        width: 30px;
        height: 30px;
        background-color: #FFFFFF;
    }

    .card__title--large {
        font-size: 20px;
        font-weight: 400;
        line-height: 30px;
    }
</style>